import 'package:base_flutter/base_flutter.dart' as b;
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:ls_work/a_elder/models/elder_entity.dart';
import 'package:ls_work/a_yyt/models/take_leave_entity.dart';
import 'package:ls_work/a_yyt/page/take_leave_add_page.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/click_item.dart';
import 'package:ls_work/widgets/my_refresh_divider_list.dart';
import 'dart:convert';
import 'package:dio/dio.dart';

import '../../util/flat_button.dart';


class TakeLeavePage extends StatefulWidget {
  final int? leaveType;
  final ElderInfo? elderModel;
  TakeLeavePage({Key? key, this.leaveType, this.elderModel});
  @override
  _TakeLeavePageState createState() => _TakeLeavePageState();
}

class _TakeLeavePageState extends State<TakeLeavePage> {
  bool isMore = false;
  int _page = 1;
  DateTime? _selectedDate = DateTime.now(); //当前选中的日期
  String _selectedTime = '';
  String _leaveDay = '';
  TextEditingController textFieldEditer = TextEditingController();
  List<TakeLeaveInfo> dataList = [];
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fectData();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return widget.leaveType != null
        ? _getBodyWidget()
        : Scaffold(
            appBar: AppBar(
              title: Text('请假管理'),
              elevation: 0.5,
              actions: [
                TextButton(
                  onPressed: () {
                    AppNavigator.push(
                      context,
                      TakeLeaveAddPage(
                        elderModel: widget.elderModel,
                        callBack: _onRefresh,
                      ),
                    );
                  },
                  child: Text(
                    '请假',
                    style: TextStyle(fontSize: 16, color: Colours.app_main),
                  ),
                )
              ],
            ),
            body: _getBodyWidget(),
          );
  }

  Widget _getBodyWidget() {
    return DeerSeparatedListView(
      key: Key('_list'),
      itemCount: dataList.length,
      onRefresh: _onRefresh,
      loadMore: _loadMore,
      hasMore: isMore,
      itemBuilder: (_, index) {
        return Container(
          child: _getLeavingItem(dataList[index]),
        );
      },
      separatorBuilder: (_, int index) => Gaps.line,
    );
  }

  Widget _getLeavingItem(TakeLeaveInfo info) {
    return ExpansionTile(
      title: info.isSelected==true
          ? (info.validSign == "2" ? _normalTitle(info) : _selectedTitle(info))
          : _normalTitle(info),
      onExpansionChanged: (value) {
        setState(() {
          info.isSelected = value;
        });
      },
      children: [
        Container(
          padding: EdgeInsets.only(left: 18),
          alignment: Alignment.centerLeft,
          child: Text(
            "离院时间：" +
                DateUtil.formatDateStr('${info.leaveTime}',
                    format: DateFormats.y_mo_d_h_m),
            style: TextStyles.textDark16,
          ),
        ),
        Gaps.vGap10,
        Container(
          padding: EdgeInsets.only(left: 18),
          alignment: Alignment.centerLeft,
          child: Text(
            "计划返院时间：" +
                DateUtil.formatDateStr('${info.planBackTime}',
                    format: DateFormats.y_mo_d_h_m),
            style: TextStyles.textDark16,
          ),
        ),
        Gaps.vGap10,
        Container(
          padding: EdgeInsets.only(left: 18),
          alignment: Alignment.centerLeft,
          child: Text(
            "离院理由：${info.leaveReasonName}",
            style: TextStyles.textDark16,
          ),
        ),
        Gaps.vGap10,
        Container(
          padding: EdgeInsets.only(left: 18),
          alignment: Alignment.centerLeft,
          child: Text(
            "陪同人员：${info.accompanyName ?? ""}",
            style: TextStyles.textDark16,
          ),
        ),
        Gaps.vGap10,
        Container(
          padding: EdgeInsets.only(left: 18),
          alignment: Alignment.centerLeft,
          child: Text(
            "请假登记人：${info.leaveRegistrantName ?? ''}",
            style: TextStyles.textDark16,
          ),
        ),
        Gaps.vGap10,
        Container(
          padding: EdgeInsets.only(left: 18),
          alignment: Alignment.centerLeft,
          child: Text(
            "登记时间：" +
                DateUtil.formatDateStr('${info.createdDate}',
                    format: DateFormats.y_mo_d_h_m),
            style: TextStyles.textDark16,
          ),
        ),
        Gaps.vGap10,
        info.validSign == "2"
            ? Container(
                padding: EdgeInsets.only(left: 18),
                alignment: Alignment.centerLeft,
                child: Text(
                  "返院时间：" +
                      DateUtil.formatDateStr('${info.backTime}',
                          format: DateFormats.y_mo_d_h_m),
                  style: TextStyles.textDark16,
                ),
              )
            : SizedBox(),
        Gaps.vGap10,
        info.validSign == "2"
            ? Container(
                padding: EdgeInsets.only(left: 18),
                alignment: Alignment.centerLeft,
                child: Text(
                  "返院登记人：${info.leaveRegistrantName ?? ''}",
                  style: TextStyles.textDark16,
                ),
              )
            : SizedBox(),
        Gaps.vGap10,
      ],
    );
  }

  Widget _normalTitle(TakeLeaveInfo info) {
    // print(info.validSign);
    return info.validSign == "2"
        ? Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text(
                '${info.customerElderName}',
                style: TextStyles.textDark18,
              ),
              Gaps.hGap10,
              Gaps.hGap10,
              Expanded(
                child: Text(
                  info.validSignName??'',
                  style: TextStyle(color: Colors.green, fontSize: 16),
                ),
              ),
              Text(
                "请假天数：${info.leaveDay}天",
                style: TextStyle(fontSize: 14, color: Colors.blue[200]),
              ),
            ],
          )
        : Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Expanded(
                  child: Text(
                '${info.customerElderName}',
                style: TextStyles.textDark18,
              )),
              Text(
                DateUtil.formatDateStr('${info.leaveTime}',
                    format: "yyyy-MM-dd"),
                style: TextStyles.textGray14,
              ),
              Gaps.hGap10,
              Text(
                info.validSignName??'',
                style: TextStyle(color: Colors.red, fontSize: 16),
              )
            ],
          );
  }

  _selectedTitle(TakeLeaveInfo info) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text(
          '${info.customerElderName}',
          style: TextStyles.textDark18,
        ),
        Gaps.hGap10,
        Gaps.hGap10,
        Expanded(
          child: Text(
            info.validSignName??'',
            style: TextStyle(
              color: info.validSign == "2" ? Colors.green : Colors.red,
              fontSize: 16,
            ),
          ),
        ),
        info.validSign == "2"
            ? Text(
                "返院时间：" +
                    DateUtil.formatDateStr(
                      '${info.backTime}',
                      format: "yyyy-MM-dd",
                    ),
              )
            :Container()
            // : SizedBox(
            //     width: 100,
            //     height: 30,
            //     child: b.FlatsButton(
            //       color: Colours.app_main,
            //       highlightColor: Colors.blue[700],
            //       child: Text("销假"),
            //       shape: RoundedRectangleBorder(
            //           borderRadius: BorderRadius.circular(8.0)),
            //       onPressed: () {
            //         _bottomDelayServiceSheetAlert(info);
            //       },
            //     ),
            //   )
      ],
    );
  }

  ///返回确认
  _bottomDelayServiceSheetAlert(TakeLeaveInfo model) {
    if (model.leaveDay != null)
      textFieldEditer.text = model.leaveDay.toString();
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: context,
      isScrollControlled: true,
      isDismissible: false,
      builder: (BuildContext context) {
        return StatefulBuilder(builder: (context, setDialogState) {
          return Stack(
            children: <Widget>[
              SingleChildScrollView(
                child: Container(
                  width: double.infinity,
                  padding: EdgeInsets.only(
                      bottom: MediaQuery.of(context).viewInsets.bottom), //
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Gaps.vGap50,
                      Text(
                        '返院确认',
                        style:
                            TextStyle(fontSize: 20, color: Colours.text_dark),
                      ),
                      Gaps.vGap15,
                      Text(
                        '${model.customerElderName}   ${model.roomNumber}',
                        style: TextStyles.textGray18,
                      ),
                      Gaps.vGap50,
                      ClickItem(
                        title: "返院时间",
                        content: _selectedTime,
                        onTap: () {
                          _showTimePicker(model, () {
                            setDialogState(() {});
                          });
                        },
                      ),
                      Gaps.vGap15,
                      ClickItem(
                        title: "请假天数",
                        content: "$_leaveDay 天",
                      ),
                      // Row(
                      //   children: [
                      //     Text("    请假天数"),
                      //     Container(
                      //       width: ScreenUtil.getScreenW(context) - 120,
                      //       padding: EdgeInsets.all(20),
                      //       color: Colors.white,
                      //       alignment: Alignment.topLeft,
                      //       height: 100,
                      //       child: TextField(
                      //         textAlign: TextAlign.center,
                      //         controller: textFieldEditer,
                      //         maxLines: 1,
                      //         autofocus: false,
                      //         keyboardType: TextInputType.number,
                      //         decoration: InputDecoration(
                      //           hintText: "请输入请假天数",
                      //           fillColor: Colours.bg_color,
                      //           filled: true,
                      //           border: InputBorder.none,
                      //         ),
                      //       ),
                      //     ),
                      //     Text("天"),
                      //   ],
                      // ),
                      Gaps.vGap50,
                      Container(
                        width: double.infinity,
                        height: 50,
                        padding: EdgeInsets.fromLTRB(12, 0, 12, 0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            FlatsButton(
                              color: Colours.text_gray,
                              onPressed: () {
                                _selectedTime = "";
                                _leaveDay = "";
                                Navigator.pop(context);
                              },
                              child: Text(
                                '取消',
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                            FlatsButton(
                              color: Colours.app_main,
                              onPressed: () {
                                // _updateServicePlanRecord(
                                //     model: model, isDelayService: true);
                                _leaveConfirm(model);
                              },
                              child: Text(
                                '确定',
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Gaps.vGap50,
                    ],
                  ),
                ),
              ),
            ],
          );
        });
      },
    );
  }

  //调起时间选择器
  _showTimePicker(TakeLeaveInfo info, VoidCallback calBack) {
    DatePicker.showDatePicker(
      context,
      minDateTime: DateTime.parse("1900-01-01 00:00"),
      maxDateTime: DateTime.parse("2099-01-01 00:00"),
      initialDateTime: DateTime.now(),
      dateFormat: "yyyy-MM-dd HH:mm",
      locale: DateTimePickerLocale.zh_cn,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        confirm: Text('确定'),
      ),
      pickerMode: DateTimePickerMode.datetime, // show TimePicker
      onConfirm: (dateTime, List<int> index) {
        DateTime? _leaveTime = DateUtil.getDateTime(info.leaveTime??'');
        if(_leaveTime==null){
          Toast.show("离院时间不可为空");
          return;
        }
        if (_leaveTime.isAfter(dateTime)) {
          Toast.show("返院确认时间，不得小于离院时间");
          return;
        }
        setState(() {
          if (dateTime == null) {
            return;
          }
          _fectLeaveDaysData(
            info,
            DateUtil.formatDate(dateTime, format: DateFormats.full),
            calBack,
          );
          _selectedDate = dateTime;
          _selectedTime =
              DateUtil.formatDate(dateTime, format: DateFormats.y_mo_d_h_m);
          calBack();
        });
      },
    );
  }

  _fectData() {
    SVProgressHUD page = SVProgressHUD(context);
    Map<String, dynamic> map = {
      'page': _page,
      'rows': 20,
    };
    if (widget.elderModel != null) {
      map['customerNameLike'] = widget.elderModel?.name??"";
    }
    if (widget.leaveType != null) {
      map['validSign'] = widget.leaveType;
    }
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.takeLeave}', data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            TakeLeaveEntity model = TakeLeaveEntity.fromJson(map['data']);
            if ((model.rows??[]).length > 0) {
              isMore = (model.rows??[]).length == 20;
              setState(() {
                if (_page == 1) {
                  /// 刷新
                  dataList.clear();
                  dataList.addAll(model.rows??[]);
                } else {
                  dataList.addAll(model.rows??[]);
                }
              });
            } else {
              setState(() {
                if (_page == 1) {
                  dataList.clear();
                  dataList.addAll(model.rows??[]);
                }
              });
              Toast.show('未查询到数据');
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///获取请假天数
  _fectLeaveDaysData(
      TakeLeaveInfo info, String backDate, VoidCallback callBack) {
    SVProgressHUD page = SVProgressHUD(context);
    Map<String, dynamic> map = {
      'leaveDate': info.leaveTime,
      'backDate': backDate,
    };
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.calculateLeaveDays}', data: FormData.fromMap(map))
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        print(map);
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            setState(() {
              _leaveDay = map["data"].toString();
              callBack();
            });
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///请假确认
  _leaveConfirm(TakeLeaveInfo info) {
    if (_selectedTime.isEmpty) {
      Toast.show("请选择返院时间");
      return;
    }
    if (_leaveDay.isEmpty) {
      Toast.show("请重新选择返院时间");
      return;
    }
    Map<String, dynamic> map = {
      'id': info.id,
      'backTime':
          DateUtil.formatDate(_selectedDate, format: 'yyyy-MM-dd HH:mm:ss'),
      'leaveDay': _leaveDay,
    };
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.confirmLeave}?${requestParams(map)}')
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          _selectedDate = null;
          Navigator.of(context).pop();
          _onRefresh();
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  Future _onRefresh() async {
    _page = 1;
    _fectData();
  }

  Future _loadMore() async {
    _page++;
    _fectData();
  }
}
